package com.hqd.ch03.v27.beans.property.support;

import com.hqd.ch03.v27.beans.PropertyValues;
import com.hqd.ch03.v27.beans.property.PropertyAccessor;
import com.hqd.ch03.v27.beans.support.TypeConverterSupport;
import com.hqd.ch03.v27.config.MutablePropertyValues;
import com.hqd.ch03.v27.config.PropertyValue;

import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public abstract class AbstractPropertyAccessor extends TypeConverterSupport implements PropertyAccessor {
    protected Class<?> clazz;

    public AbstractPropertyAccessor(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setPropertyValue(PropertyValue pv) {
        setPropertyValue(pv.getName(), pv.getValue());
    }

    @Override
    public void setPropertyValues(Map<?, ?> map) {
        //TODO map初始化
    }

    @Override
    public void setPropertyValues(PropertyValues pvs) {
        setPropertyValues(pvs, false, false);
    }

    @Override
    public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown) {
        setPropertyValues(pvs, ignoreUnknown, false);
    }

    @Override
    public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid) {

        List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
                ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));

        for (PropertyValue pv : propertyValues) {
            try {
                setPropertyValue(pv);
            } catch (Exception ex) {
                throw ex;
            }
        }
    }

    @Override
    public Class<?> getPropertyType(String propertyName) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
            return pd.getPropertyType();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public abstract Object getPropertyValue(String propertyName);

    @Override
    public abstract void setPropertyValue(String propertyName, Object value);

}
